import './login.scss'
import { Button, Form, Input, message } from 'antd'
import { useState, useEffect } from 'react'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'

function Login() {
  const navigate = useNavigate()

  const [passwordVisible, setPasswordVisible] = useState(false)
  const [userInfo, setUserInfo] = useState({
    username: 'admin',
    password: '123456',
  })

  const [form] = Form.useForm()

  useEffect(() => {
    form.setFieldsValue(userInfo)
  }, [userInfo, form])

  const handleValuesChange = (_: any, allValues: any) => {
    setUserInfo(allValues)
  }

  // 点击登录按钮的回调
  const handleLogin = () => {
    if (userInfo.username === 'admin' && userInfo.password === '123456') {
      navigate('/')
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    } else {
      message.error('用户名或密码错误')
    }
  }

  useEffect(() => {
    JSON.parse(localStorage.getItem('userInfo') as string) && navigate('/')
  }, [])

  return (
    <div className="Login">
      <div className="left">
        <div className="left-img">
          <img src="/assets/images/font.png" alt="" />
          <span>慧教云</span>
        </div>
      </div>
      <div className="right">
        <div className="rightForm">
          <Form
            form={form}
            name="basic"
            size="large"
            labelCol={{ span: 4 }}
            labelAlign="left"
            wrapperCol={{ span: 24 }}
            onValuesChange={handleValuesChange}
            autoComplete="off"
          >
            <Form.Item>
              <span style={{ fontWeight: '600', fontSize: '25px' }}>管理员登录</span>
            </Form.Item>
            <Form.Item name="username">
              <Input placeholder="请输入用户名" prefix={<UserOutlined />} />
            </Form.Item>
            <Form.Item name="password">
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="请输入密码"
                visibilityToggle={{ visible: passwordVisible, onVisibleChange: setPasswordVisible }}
              />
            </Form.Item>
            <Form.Item>
              <Button onClick={handleLogin} className="btn" type="primary">
                立即登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  )
}

export default Login
